<template>
  <div class="schedule">
    <configCompositionTwoWindowStyle
      :leftWidth = "10"
      :rightWidth="14"
    >
      <template slot="card">
        <search
          @active="active"
          :showAdvSearch="false"
          :isShowInput="false"
          :showAdd="false"
          @advSearch="advSearch"
          :advSearchData="advSearchData"
          :inputTitle="'输入服务号进行查询'"
          :loading="tableLoading"
          @refresh="refresh"
          @search="searchByName"
          @turnPage="turnPage"
          @roloadIvrSucc="roloadIvrSucc"
          :currentPage="currentPage"
          :count="count"
          :reload="reload"
          :pageSize="pageSize">
        </search>
        <template>
          <el-row :gutter="20" style="border-top: 1px solid #d9d9d9;padding: 6px;margin: 0px">
            <el-col :span="12">
              <el-select size="mini" v-model="PBX" @change="ToChangePBX" style="width: 100%">
                <el-option
                        :label="$t('public.all')"
                        :key="'kong'"
                        :value="''">
                </el-option>
                <el-option
                        v-for="(item, index) in pbxs"
                        :key="index"
                        :label="item.NickName + ' (' +item.PBX + ')'"
                        :value="item.PBX">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-input
                :placeholder="$t('channelsettings.schedule1')"
                class="condition"
                size="mini"
                v-model="searchContent"
                @keyup.enter.native="handleIconClick"
                >
                <i
                  class="el-input__icon el-icon-search"
                  slot="suffix"
                  @click="handleIconClick">
                </i>
              </el-input>
            </el-col>
          </el-row>
        </template>
        <scheduleTab :tableData="tableData" @updata="updata" @del="del" @add="add" :loading="tableLoading" ref="scheduleTable"></scheduleTab>
      </template>
      <template slot="detail">
        <BreadCrumbConfig v-if="isShowAddOrEdit" :titleArr="titleArr" @back="cancle"></BreadCrumbConfig>
        <div>
          <editSchedule v-if="isShowEdit"
                        ref="editSch"
                       :tableData="editData"
                       :editScheduleInfo="editScheduleInfo"
                       @editRefresh="editRefresh"></editSchedule>
        </div>
        <div>
          <addSchedule v-if="isShowAdd"
                       :addScheduleInfo = "addScheduleInfo"
                       @addRefresh="addRefresh"></addSchedule>
        </div>
      </template>
    </configCompositionTwoWindowStyle>
  </div>
</template>
<script>
  import configCompositionTwoWindowStyle from '../../../../ui-modules/config/configCompositionTwoWindowStyle'
  import search from '../base/search'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
  import scheduleTab from '../base/scheduleTab'
  import editSchedule from '../base/editSchedule.vue'
  import {deepClone, ivrSearch} from '@/utils/m7Utils'
  import addSchedule from '../base/addSchedule'
  export default {
    name: 'schedule',
    data () {
      return {
        norSearch: [],
        pageSize: 10,
        PBX: '',
        pbxs: [],
        searchContent: '',
        addScheduleInfo: {},
        reload: true,
        isShowAdd: false,
        isShowEdit: false,
        advSearchData: {
          items: [
            {
              title: '服务号类型',
              type: 'select',
              valueName: 'Type',
              data: [
                {label: '普通', value: 'normal'},
                {label: '轻量级', value: 'lightweight'}
              ]
            },
            {
              title: '服务号',
              type: 'input',
              valueName: 'Exten'
            }
          ],
          form: {Type: '', Exten: ''}
        },
        availableService: [],
        dataList: [],
        count: 0,
        agents: [],
        currentPage: 1,    //   当前页
        tableData: [],           //  表格数据
        tableLoading: false,      //   表格  loading
        isShowAddOrEdit: false,   //   右侧  新建或修改 显隐
        titleArr: [this.$t('channelsettings.schedule2'), this.$t('channelsettings.schedule3')],
        inputName: '',
        editScheduleInfo: {},
        editData: {},
        currentServerNo: ''
      }
    },
    components: {
      addSchedule,
      configCompositionTwoWindowStyle,
      search,
      BreadCrumbConfig,
      scheduleTab,
      editSchedule
    },
    methods: {
      cancle () {
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
      },
      ToChangePBX () {
        this.currentPage = 1
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        this.tableData = []
        let dataArray = []
        this.norSearch = []
        if (this.searchContent) {
          dataArray = ivrSearch(this.dataList, this.searchContent, ['Exten'])
        } else {
          dataArray = deepClone(this.dataList)
        }
        dataArray.forEach(item => {
          if (this.PBX) {
            if (item.PBX === this.PBX) {
              this.norSearch.push(item)
            }
          } else { // 选择全部时
            this.norSearch.push(item)
          }
        })
        this.tableData = []
        this.handleFakePage(this.norSearch)
        this.count = this.norSearch.length
        this.handleIconClick()
      },
      handleIconClick (flag) {
        if (!(flag === 'search' && this.currentServerNo)) {
          this.currentPage = 1
        }
        console.log(this.searchContent)
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        this.tableData = []
        let dataArray = []
        let ids = []
        this.norSearch = []
        if (this.PBX) {
          dataArray = ivrSearch(this.dataList, this.PBX, ['PBX'])
        } else {
          dataArray = deepClone(this.dataList)
        }
        dataArray.forEach(item => {
          if (item.Exten.indexOf(this.searchContent) !== -1) {
            if (ids.indexOf(item._id) === -1) {
              this.norSearch.push(item)
              ids.push(item._id)
            }
          }
          if (item.SchedulesList && item.SchedulesList.length > 0) {
            item.SchedulesList.forEach((item1) => {
              if (item1.DisplayName.indexOf(this.searchContent) !== -1) {
                if (ids.indexOf(item._id) === -1) {
                  this.norSearch.push(item)
                  ids.push(item._id)
                }
              }
            })
          }
        })
        this.tableData = []
        this.handleFakePage(this.norSearch)
        this.count = this.norSearch.length
        if (flag === 'search' && this.currentServerNo) {
          this.$nextTick(() => {
            this.$refs.scheduleTable.rowClick({Exten: this.currentServerNo})
          })
        }
      },
      active () {},
//      添加日程
      add (val) {
        this.isShowAddOrEdit = true
        this.isShowEdit = false
        this.titleArr = [this.$t('channelsettings.schedule2'), this.$t('channelsettings.schedule3')]
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
          this.isShowAdd = true
          this.addScheduleInfo = val
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = val.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            if (res && res.success) {
              this.isShowAdd = true
              this.addScheduleInfo = val
            }
          })
        }
      },
//      修改日程
      updata (val) {
        console.log(val)
        console.log(this.tableData)
        this.isShowAddOrEdit = true
        this.isShowAdd = false
        this.titleArr = [this.$t('channelsettings.schedule2'), this.$t('channelsettings.schedule6')]
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
          this.isShowEdit = true
          this.editScheduleInfo = val
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].Exten === val.ServiceNo) {
              this.editData = deepClone(this.tableData[i])
              this.$nextTick(function () {
                this.$refs.editSch.changeData(this.editScheduleInfo)
                this.$refs.editSch.ToChangePeer(this.editScheduleInfo.ToPeerType)
              })
            }
          }
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = val.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            this.isShowEdit = true
            this.editScheduleInfo = val
            for (let i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].Exten === val.ServiceNo) {
                this.editData = deepClone(this.tableData[i])
                this.$nextTick(function () {
                  this.$refs.editSch.changeData(this.editScheduleInfo)
                  this.$refs.editSch.ToChangePeer(this.editScheduleInfo.ToPeerType)
                })
              }
            }
          })
        }
      },
//      高级搜索
      advSearch (val) {
        this.inputName = ''
        let data = {}
        data.Account = this.$store.state.session.account.account
        val.Type && (data.Type = val.Type)
        val.Exten && (data.Exten = val.Exten)
        val.PBX && (data.PBX = val.PBX)
        this.search(data)
      },
//      添加日程成功刷新
      addRefresh (data) {
        this.reload = false
        this.refresh(data)
      },
      roloadIvrSucc () {
        this.reload = true
      },
      editRefresh (data) {
        this.reload = false
        this.refresh(data)
      },
//      刷新
      refresh (data) {
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        // this.PBX = ''
        this.search({Account: this.$store.state.session.account.account}, {Account: this.$store.state.session.account.account}, data)
      },
//      input 搜索
      searchByName (val) {
        console.log(val)
        this.inputName = val
        this.norSearch = ivrSearch(this.dataList, val, ['Exten'])
        this.tableData = []
        for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < this.norSearch.length; i++) {
          this.tableData.push(this.norSearch[i])
        }
        this.count = this.norSearch.length
      },
//      初始化数据
      search (data1, data2, serviceNo) {
        // this.currentPage = 1
        this.tableData = []
        let _pageList = []
        this.tableLoading = true
        let p1 = this.$store.dispatch('queryServiceNo', data1)
        let p2 = this.$store.dispatch('querySchedule', data2)
        Promise.all([p1, p2]).then(([resp1, resp2]) => {
          if (resp1.success && resp2.success) {
            this.tableData = []
            if (resp1.list) {
              resp1.list.forEach(item => {
                if (item.Type === 'normal') {
                  let obj = {
                    Account: item.Account,
                    PBX: item.PBX,
                    Exten: item.Exten,
                    DisplayName: item.DisplayName,
                    Schedules: item.Schedules,
                    ToPeer: item.ToPeer,
                    Type: item.Type,
                    UpdateTime: item.UpdateTime,
                    UpdateUser: item.UpdateUser,
                    _id: item._id,
                    SchedulesList: []
                  }
                  _pageList.push(obj)
                }
              })
              this.count = _pageList.length
              if (resp2.list) {
                _pageList.forEach((item1, index1) => {
                  resp2.list.forEach((item2, index2) => {
                    if ((item1.Exten === item2.ServiceNo) && (item1.PBX === item2.PBX)) {
                      _pageList[index1].SchedulesList.push(item2)
                    }
                  })
                })
              }
            }
          }
          this.dataList = []
          for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _pageList.length; i++) {
            this.tableData.push(_pageList[i])
          }
          this.dataList = deepClone(_pageList)
          if (serviceNo) {
            this.$nextTick(() => {
              this.$refs.scheduleTable.rowClick({Exten: serviceNo})
            })
            this.currentServerNo = serviceNo
          }
          if (this.searchContent) {
            this.handleIconClick('search')
          }
          if (this.PBX) {
            this.ToChangePBX()
          }
        })
      },
      handleFakePage (_array) {
        for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _array.length; i++) {
          this.tableData.push(_array[i])
        }
      },
      turnPage (val) {
        this.currentPage = val
        this.tableData = []
        if (this.searchContent === '' && this.PBX === '') {
          this.handleFakePage(this.dataList)
        } else {
          this.handleFakePage(this.norSearch)
        }
//        this.search({Account: this.$store.state.session.account.account})
      },
//      删除服务号
      del (_schedule) {
        console.log(_schedule)
        let data = {
          ServiceNo: _schedule.ServiceNo,
          DisplayName: _schedule.DisplayName,
          Order: _schedule.Order,
          StartDate: _schedule.StartDate,
          EndDate: _schedule.EndDate,
          StartTime: _schedule.StartTime,
          EndTime: _schedule.EndTime,
          WeekMon: _schedule.WeekMon,
          WeekTue: _schedule.WeekTue,
          WeekWed: _schedule.WeekWed,
          WeekThu: _schedule.WeekThu,
          WeekFri: _schedule.WeekFri,
          WeekSat: _schedule.WeekSat,
          WeekSun: _schedule.WeekSun,
          ToPeer: _schedule.ToPeer,
          ToPeerType: _schedule.ToPeerType,
          IvrProcessId: _schedule.IvrProcessId,
          Account: _schedule.Account,
          PBX: _schedule.PBX,
          AnnouncementId: _schedule.AnnouncementId,
          _id: _schedule._id
        }
        this.$confirm(this.$t('config.channel.deleteManageConfirm'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteSchedule', data).then(res => {
            if (res && res.success) {
              this.refresh(_schedule.ServiceNo)
              this.reload = false
              this.$message({
                message: this.$t('config.channel.deleteSuccess'),
                type: 'success'
              })
            } else {
              this.$message.error(this.$t('config.channel.deleteFailure'))
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      }
    },
    mounted () {
    },
    beforeMount () {
      this.pbxs = this.$store.state.session.account.pbx
      this.search({Account: this.$store.state.session.account.account}, {Account: this.$store.state.session.account.account})
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
</style>
